package com.ultrasoft.farmasoft.repository;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ultrasoft.farmasoft.domain.Submenu;


@Repository(value = "subMenuDao")
@Transactional(readOnly = false)
public class SubMenuDaoImpl implements SubMenuDao {
	
	private EntityManager em = null;	
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	@SuppressWarnings("unchecked")
	public List<Submenu> getSubMenuList() {
		return em.createNamedQuery("Submenu.findAll").getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Submenu> getSubMenuList(short menuId) {
		Query  q =em.createNamedQuery("Submenu.findByMenuId");
		q.setParameter("menuId",menuId);		
		return getInOderSubMenu(q.getResultList());
	}

	@SuppressWarnings("unchecked")
	private List<Submenu> getInOderSubMenu(List<Submenu> list){
		Collections.sort(list, new Comparator() {  			  
	            public int compare(Object o1, Object o2) {  
	                Submenu e1 = (Submenu) o1;  
	                Submenu e2 = (Submenu) o2;  
	                short codigo1 = e1.getOrder();  
	                short codigo2 = e2.getOrder(); 
	                if (codigo1 > codigo2) {  
	                    return 1;  
	                } else if (codigo1 < codigo2) {  
	                    return -1;  
	                } else {  
	                    return 0;  
	                }  
	            }  
	        });  
		return list;
	}
	public Submenu findByMenuIdBySubmenuId(short menuId, short submenuId) {
		Submenu res=null;
    	Query  q = em.createNamedQuery("Submenu.findByMenuIdBySubmenuId");
    	q.setParameter("menuId",menuId);
    	q.setParameter("submenuId",submenuId);
    	if(q.getResultList().size()==1)
    		res=(Submenu)q.getSingleResult();
    	return res;
	}

	public void add(Submenu submenu) {
		em.persist(submenu);
	}

}
